package tf2pickup.listeners;

import org.pircbotx.hooks.ListenerAdapter;
import org.pircbotx.hooks.events.ConnectEvent;
import org.pircbotx.hooks.events.DisconnectEvent;
import org.pircbotx.PircBotX;

import tf2pickup.Config;

/**
 * Provides basic features for the IRC, including:
 * - joining the channel specified in the configuration
 * - auth with Q
 * - try to reconnect on disconnect (not implemented yet)
 * @author Philipp Preß
 */
public class OnConnect extends ListenerAdapter<PircBotX> {

    private Config cfg;

    /**
     * Will execute the onConnect-method when connecting to an irc-server.
     * @param cfg configuration-file of the bot.
     */
    public OnConnect(Config cfg) {
        this.cfg = cfg;
    }

    /**
     * Method gets executed when the bot connected to an irc-channel. once
     * called, it will auth with Q and join the specified irc-channel.
     * @param event the dispatched event.
     */
    @Override
    public void onConnect(ConnectEvent<PircBotX> event) {
        this.AuthWithQ(event.getBot());
        this.joinChannel(event.getBot());
    }

    /**
     * Method gets executed when the bot gets disconnected from the irc-server.
     * @param event 
     */
    @Override
    public void onDisconnect(DisconnectEvent<PircBotX> event) {
//        while (!event.getBot().isConnected()) {
//            //Try reconnect
//        }
    }

    /*
     * auth with Q by sending /auth xxx xxx command to the irc-server.
     */
    private void AuthWithQ(PircBotX bot) {
        bot.sendRawLine("auth " + cfg.ircAuthNickname + " " + cfg.ircAuthPassword);
    }

    /**
     * joins the specified channel.
     * @param bot 
     */
    private void joinChannel(PircBotX bot) {
        if (cfg.ircChannelPassword != null) {
            bot.joinChannel(cfg.ircChannel, cfg.ircChannelPassword);
            return;
        }
        bot.joinChannel(cfg.ircChannel);
    }
}